package com.mes.web.controller.yzl;

import com.mes.entity.hpf.SaleOutDetail;
import com.mes.entity.hpf.SalePlanDetail;
import com.mes.entity.tdd.Staff;
import com.mes.entity.yzl.*;
import com.mes.entity.yzlExtend.ExtendOutlib;
import com.mes.entity.yzlExtend.ExtendProductor;
import com.mes.service.yzl.OutlibService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/yzl")
public class OutlibController {

    protected Logger logger = Logger.getLogger(OutlibController.class);
    private static final long serialVersionUID = 8550329576989690578L;

    @Resource
    OutlibService outlibService;

    @RequestMapping("/outLibNumLast")
    public @ResponseBody Map outLibNumLast(HttpSession session){

    	Map map = new HashMap();
        String returnNumber = "";
        returnNumber = outlibService.outLibNumLast();
        map.put("returnNumber", returnNumber);
        Staff staff = (Staff) session.getAttribute("staff");
        map.put("staff", staff);
        return map;

    }

    @RequestMapping("/addOutfrom")
    public @ResponseBody int addOutfrom(@RequestBody Object obj) throws ParseException {
        int isSuccess = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);
        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        OutLib outLib = new OutLib();
        outLib.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        outLib.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        outLib.setOutDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));
        outLib.setOutNumber((String)jsonObject.get("number"));
        outLib.setOutStatus("0");
        outLib.setSpStatus("0");
        outLib.setIsSelect("0");

        //isSuccess = outlibService.addOutOrderAll(outLib,jsonArray);

        long addIsSuccess = 0;
        addIsSuccess = outlibService.addOutOrder(outLib);

        if(addIsSuccess > 0){
            for(int i = 0;i<jsonArray.size();i++){
                JSONObject jObj = (JSONObject) jsonArray.get(i);
                int out = jObj.getInt("outQ");
                int lastPlanQ = jObj.getInt("lastPlanQ");
                SaleOutDetail saleOutDetail = new SaleOutDetail();
                saleOutDetail.setOutLibId(addIsSuccess);
                saleOutDetail.setProductorId(jObj.getLong("pid"));
                saleOutDetail.setOutQ(out);
                saleOutDetail.setLastOutQ(out);
                saleOutDetail.setLastPlanQ(lastPlanQ);
                saleOutDetail.setAddReturnIsSelect("0");
                saleOutDetail.setPlanDetailID(jObj.getLong("planId"));
                outlibService.addOutDetail(saleOutDetail);
                if (lastPlanQ == out) {
                	SalePlanDetail salePlanDetail = new SalePlanDetail();
                	salePlanDetail.setLastPlanQ(lastPlanQ-out);
                	salePlanDetail.setAddOutIsSelect("1");
                	salePlanDetail.setId(jObj.getLong("planId"));
                	outlibService.updatePlanDetailStatus(salePlanDetail);
				} else {
					SalePlanDetail salePlanDetail = new SalePlanDetail();
					salePlanDetail.setLastPlanQ(lastPlanQ-out);
                	salePlanDetail.setAddOutIsSelect("0");
                	salePlanDetail.setId(jObj.getLong("planId"));
                	outlibService.updatePlanDetailStatus(salePlanDetail);
				}
            }
            isSuccess = 1;
        }

        return isSuccess;
    }

    //条件分页查询
    @RequestMapping("/outLibOrderList")
    public @ResponseBody ListBack customerOrderList(Condition condition){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ListBack listBack = new ListBack();
        List<ExtendOutlib> outLibs = new ArrayList<>();

        //查询条件处理
        Sup sup = new Sup();
        condition = sup.tdSet(condition);

        //条件查询总数
        int count = outlibService.countOutlibCount(condition);
        listBack.setTotal(count);
        //条件分页查询
        outLibs = outlibService.listOutlibList(condition);
        listBack.setRows(outLibs);
        return listBack;
    }
    
    //条件分页查询
    @RequestMapping("/cusOrderList")
    public @ResponseBody ListBack cusOrderList(Condition condition){
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	ListBack listBack = new ListBack();
    	List<SalePlanDetail> outLibs = new ArrayList<>();
    	
    	//查询条件处理
    	Sup sup = new Sup();
    	condition = sup.tdSet(condition);
    	
    	//条件查询总数
    	int count = outlibService.cusOrderCount(condition);
    	listBack.setTotal(count);
    	//条件分页查询
    	outLibs = outlibService.cusOrderList(condition);
    	listBack.setRows(outLibs);
    	return listBack;
    }
    
    //添加出库单的计划详情
    @RequestMapping("/addCusOrderXq")
    public @ResponseBody List<ExtendProductor> addCusOrderXq(long id){
    	List<ExtendProductor> extendProductors = new ArrayList<>();
        extendProductors = outlibService.addCusOrderXq(id);
        return extendProductors;
    }

    //根据ID查询出库单
    @RequestMapping("/findOutorderById")
    public @ResponseBody ExtendOutlib findOutorderById(long id){
        ExtendOutlib extendOutlib = new ExtendOutlib();
        extendOutlib = outlibService.findOutorderById(id);
        return extendOutlib;
    }

    //更新
    @RequestMapping("/updateOutLibFrom")
    public @ResponseBody int updateOutLibFrom(@RequestBody Object obj) throws ParseException {
        int isSuccess = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);

        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        //先去更新出库单
        OutLib outLib = new OutLib();
        outLib.setId(jsonObject.getLong("id"));
        outLib.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        outLib.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        outLib.setOutDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));
        long updateIsSuccess = 0;
        updateIsSuccess = outlibService.updateOutLib(outLib);

        if(updateIsSuccess > 0){
            //更新对应的产品  暂时不可以添加产品或者删除产品
            for(int i = 0;i<jsonArray.size();i++){
                JSONObject jObj = (JSONObject) jsonArray.get(i);
                int oldOutQ = jObj.getInt("outQ");
                int outQ = jObj.getInt("planQ");
                int lastPlanQ = jObj.getInt("lastPlanQ");
                int rLastPlanQ = jObj.getInt("rLastPlanQ");
                SaleOutDetail saleOutDetail = new SaleOutDetail();
                saleOutDetail.setId(jObj.getLong("id"));
                saleOutDetail.setOutQ(outQ);
                saleOutDetail.setLastOutQ(outQ);
                saleOutDetail.setLastPlanQ(lastPlanQ);
                //logger.info("jObj---------"+jObj);
                outlibService.updateOutDetail(saleOutDetail);
                if ((oldOutQ+rLastPlanQ) == outQ) {
                	SalePlanDetail salePlanDetail = new SalePlanDetail();
                	salePlanDetail.setLastPlanQ(oldOutQ+rLastPlanQ-outQ);
                	salePlanDetail.setAddOutIsSelect("1");
                	salePlanDetail.setId(jObj.getLong("planDetailID"));
                	outlibService.updatePlanDetailStatus(salePlanDetail);
				} else {
					SalePlanDetail salePlanDetail = new SalePlanDetail();
					salePlanDetail.setLastPlanQ(oldOutQ+rLastPlanQ-outQ);
                	salePlanDetail.setAddOutIsSelect("0");
                	salePlanDetail.setId(jObj.getLong("planDetailID"));
                	outlibService.updatePlanDetailStatus(salePlanDetail);
				}
            }
            isSuccess = 1;
        }
        return isSuccess;
    }
    
    /***
     * 2018/3/25
     * 侯鹏飞
     * @param ids
     * @return
     */
    @RequestMapping("/deleteOutLibOrder")
    public @ResponseBody int deleteOutLibOrder(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        for (int i = 0; i < list.size(); i++) {
            //删除销售出库
            int deleteOrder = outlibService.deleteOutLibOrder(list.get(i));
            
            if (deleteOrder>0) {
            	
            	outlibService.deleteOutDetail(list.get(i));
            }
            isSuccess = deleteOrder;
		}
        return isSuccess;
    }

    //底部详情
    @RequestMapping("/outOrderXq")
    public @ResponseBody List<SaleOutDetail> outOrderXq(long id){
        List<SaleOutDetail> saleOutDetails = new ArrayList<>();
        saleOutDetails = outlibService.outDetail(id);
        return saleOutDetails;
    }

    @RequestMapping("/outLibList")
    public @ResponseBody List<OutLib> outLibList(){
        List<OutLib> outLibs = new ArrayList<>();
        outLibs = outlibService.outLibList();
        return outLibs;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //出库处理
    @RequestMapping("/libOutbound")
    public @ResponseBody int libOutbound(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        for (int i = 0; i < list.size(); i++) {
        	List<ExtendProductor> outProList = outlibService.outOrderXq(list.get(i));
        	List<Integer> customerOrderIds = new ArrayList<Integer>();
        	for (int j = 0; j < outProList.size(); j++) {
				if (!customerOrderIds.contains(outProList.get(j).getCustomerOrderId())) {
					customerOrderIds.add(outProList.get(j).getCustomerOrderId());
				}
			}
        	for (int j = 0; j < customerOrderIds.size(); j++) {
        		List<ExtendProductor> orderProList = outlibService.orderXq(customerOrderIds.get(j));
        		for(int k=0;k<orderProList.size();k++){
            		int num = 0;
            		ProContactOrder proContactOrder = outlibService.findCusCenterProByPid(orderProList.get(k).getPid());
            		ExtendOutlib outlib = outlibService.findOutorderById(proContactOrder.getOutLibId());
            		if(outlib==null){
            			num = 1;
            		}else if(outlib.getOutStatus().equals("0")&&outlib.getId()!=list.get(i)){
                		num = 1;
                	}else{
                		num = 0;
            		}
                	if(num==0){
                		list1.add(customerOrderIds.get(j));
                	}else{
                		list2.add(customerOrderIds.get(j));
                	}
            	}
			}
		}
        isSuccess = outlibService.libOutbound(list);
        if(list1.size()!=0){
        	isSuccess = outlibService.cusOrderbound(list1);
        }
        if(list2.size()!=0){
        	isSuccess = outlibService.cusOrderboundTwo(list2);
        }
        return isSuccess;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //提交审核
    @RequestMapping("/outlibApproveds")
    public @ResponseBody int outlibApproveds(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = outlibService.outlibApproveds(list);
        return isSuccess;
    }

    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //撤销审核
    @RequestMapping("/outlibUnApproveds")
    public @ResponseBody int outlibUnApproveds(@RequestParam(value = "arr") String arr){
        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = outlibService.outlibUnApproveds(list);
        return isSuccess;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @return
     * @throws IOException
     */
    //导出
    @RequestMapping("/outlibImport")
    public void outlibImport(HttpServletResponse response) throws IOException{
        List<OutLib> outlibList = outlibService.outLibList();
        String[] headers = { "序号" ,"出库单号", "出库日期", "客户", "状态", "审批状态" };
	 	//创建HSSFWorkbook对象(excel的文档对象)
	 	Workbook wb=new XSSFWorkbook();
	 	//建立新的sheet对象（excel的表单）
	 	Sheet sheet=wb.createSheet("销售出库表");
	 	// 设置表格默认列宽度
        sheet.setDefaultColumnWidth(40);  
        // 产生表格标题行  
        Row row=sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {  
        	row.createCell(i).setCellValue(headers[i]);
        }
		for (int i = 0; i < outlibList.size(); i++) {
			Row row2=sheet.createRow(i+1);
			row2.createCell(0).setCellValue(i+1);
			row2.createCell(1).setCellValue(outlibList.get(i).getOutNumber());
			row2.createCell(2).setCellValue(outlibList.get(i).getOutDate().toString());
			row2.createCell(3).setCellValue(outlibList.get(i).getName());
			if (outlibList.get(i).getOutStatus().equals("0")) {
				row2.createCell(4).setCellValue("未出库");
			} else {
				row2.createCell(4).setCellValue("已出库");
			}
			if (outlibList.get(i).getSpStatus().equals("0")) {
				row2.createCell(5).setCellValue("未提交审核");
			} else if (outlibList.get(i).getSpStatus().equals("1")) {
				row2.createCell(5).setCellValue("审核中");
			} else {
				row2.createCell(5).setCellValue("审核通过");
			}
		}
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(new Date());
		String fileName = nowtime+"销售出库表.xlsx";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
